package com.zyark.web.util;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerServer;
import org.fastdfs.client.impl.AbstractClientImpl;
import org.fastdfs.pool.ITrackerServerPool;
import org.fastdfs.pool.impl.LinkedQueueTrackerPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by ron on 17-4-12.
 */

public class FasfdfsClientUtil extends AbstractClientImpl {

    private Logger logger = LoggerFactory.getLogger(FasfdfsClientUtil.class);


    private int poolSize = 20;

    private int BUFFER_SIZE = 2048;

    private ITrackerServerPool pool = null;


    public FasfdfsClientUtil() {
        createPool();
    }

    private String imageServer = "127.0.0.1/";

    private int waitTime = 3;


    public void setImageServer(String imageServer) {
        this.imageServer = imageServer;
    }


    public void setWaitTime(int waitTime) {
        this.waitTime = waitTime;
    }

    public void createPool() {
        try {
            String clienConfigPath = new File(FasfdfsClientUtil.class.getResource("/").getFile()).getCanonicalPath()
                    + "/" + "fdfs_client.conf";
            //String file=FasfdfsClientUtil.class.getResource("/fdfs_client.conf");
            KLogger.info(clienConfigPath);
            pool = new LinkedQueueTrackerPool(clienConfigPath, poolSize);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String upload(File file) throws Exception {

        TrackerServer ts = null;
        try {
            ts = pool.geTrackerServer(waitTime);
            System.out.print(ts);
            StorageClient1 client1 = new StorageClient1(ts, null);
            return imageServer + client1.upload_file1(file2Byte(file), getFileTypeName(file.getName()), null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.pool.close(ts);
        }
        return null;
    }


    public String uploadMutipartFile(MultipartFile file) throws Exception {
        logger.info("==========" + file.getOriginalFilename() + "===" + file.getContentType());

        TrackerServer ts = null;

        try {
            ts = pool.geTrackerServer();
            System.out.print(ts);
            StorageClient1 storageClient1 = new StorageClient1(ts, null);
            return imageServer + storageClient1.upload_file1(inputStreamToByte(file.getInputStream()),
                    getFileTypeName(file.getOriginalFilename()), null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.pool.close(ts);
        }
        return null;
    }

    @Override
    public String upload(File file, NameValuePair... nameValuePairs) throws Exception {
        TrackerServer ts = null;
        try {
            ts = pool.geTrackerServer(waitTime);
            StorageClient1 client1 = new StorageClient1(ts, null);
            System.out.print(ts);
            return imageServer + client1.upload_file1(file2Byte(file), getFileTypeName(file.getName()), nameValuePairs);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.pool.close(ts);
        }
        return null;
    }

    @Override
    public File download(String fileName, String localPath) throws Exception {
        TrackerServer ts = null;
        try {
            ts = pool.geTrackerServer();
            StorageClient1 client1 = new StorageClient1(ts, null);
            return this.byte2File(client1.download_file1(fileName), localPath, UUID.randomUUID().toString() + "." +
                    getFileTypeName(fileName));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            this.pool.close(ts);
        }
    }

    @Override
    public boolean remove(String fileName) throws Exception {

        String deleteFileName = "";
        if (fileName != null) {
            deleteFileName = fileName.replace(imageServer, "");
        }
        boolean result = false;
        TrackerServer ts = null;
        try {
            ts = this.pool.geTrackerServer(waitTime);
            StorageClient1 client1 = new StorageClient1(ts, null);
            result = client1.delete_file1(deleteFileName) == 0 ? true : false;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            this.pool.close(ts);
        }
        return result;
    }

    @Override
    public NameValuePair[] getFileMate(String fileName) throws Exception {
        TrackerServer ts = null;
        try {
            ts = pool.geTrackerServer(waitTime);
            StorageClient1 client1 = new StorageClient1(ts, null);
            return client1.get_metadata1(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            this.pool.close(ts);
        }
    }

    public byte[] inputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] date = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = in.read(date, 0, BUFFER_SIZE)) != -1) {
            outputStream.write(date, 0, count);
        }
        date = null;
        return outputStream.toByteArray();
    }

}
